package xyz.csmcool.imoss.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import xyz.csmcool.imoss.config.UploadTypeEnum;
import xyz.csmcool.imoss.entity.OssConfig;
import xyz.csmcool.imoss.mapper.OssConfigMapper;
import xyz.csmcool.imoss.service.UploadFile;
import xyz.csmcool.imoss.utils.NameUtil;

import java.io.File;

/**
 * @author 什锦
 * @Package xyz.csmcool.imoss.service.impl
 * @since 2022/8/5 14:34
 */

@Component
@RequiredArgsConstructor
public class TencentUpload implements UploadFile {

    final OssConfigMapper ossConfigMapper;

    @Override
    public UploadTypeEnum getUploadType() {
        return UploadTypeEnum.TENCENT;
    }


    @Override
    public String upload(File file, String prefix) {
        OssConfig ossConfig = ossConfigMapper.selectConfig();
        //生成唯一文件名
        String newFileName = NameUtil.generateUniqueName(file.getName());
        //文件在存储桶中的key
        String key = ossConfig.getPrefix()+ prefix + newFileName;
        //声明客户端
        COSClient cosClient=null;
        System.out.println("-------------开始传输文件");
        try {
            //初始化用户身份信息(secretId,secretKey)
            COSCredentials cosCredentials = new BasicCOSCredentials(ossConfig.getSecretId(), ossConfig.getSecretKey());
            //设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(ossConfig.getRegion()));
            //这里建议设置使用 https 协议
            clientConfig.setHttpProtocol(HttpProtocol.https);
            //生成cos客户端
            cosClient = new COSClient(cosCredentials, clientConfig);
            //创建存储对象的请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), key, file);
            //执行上传并返回结果信息
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            return ossConfig.getUrl()+ "/"+ key;
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return null;
    }

}
